package back.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSONObject;

import common.pojo.InfoEnum;
import common.servlet.BaseServlet;
import common.util.ConstatFinalUtil;
import common.util.PageInfoUtil;
import users.pojo.AAdmins;
import users.pojo.ARole;
import users.service.IUsersDbService;
import users.service.impl.UsersDbServiceImpl;

/***
 * 登录后的访问界面
 * @author lby
 *
 */
@WebServlet(urlPatterns = "/back/AdminsBackServlet")
@MultipartConfig
public class AdminsBackServlet extends BaseServlet
{
	private IUsersDbService usersDbService = new UsersDbServiceImpl();
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String method = request.getParameter("method");
		if("main".equalsIgnoreCase(method))
		{
			/* 打开登陆页面 */
			main(request,response);
		}else if("welcome".equalsIgnoreCase(method))
		{
			/* 打开欢迎页面 */
			welcome(request,response);
		}else if("logout".equalsIgnoreCase(method))
		{
			/* 退出 */
			logout(request,response);
		}else if("adminsList".equalsIgnoreCase(method))
		{
			/* 管理员列表 */
			adminsList(request,response);
		}else if("adminsInsert".equalsIgnoreCase(method))
		{
			/* 管理员添加页面 */
			adminsInsert(request,response);
		}else if("adminsInsertSubmit".equalsIgnoreCase(method))
		{
			/* 管理员添加提交操作 */
			adminsInsertSubmit(request,response);
		}else if("adminsUpdate".equalsIgnoreCase(method))
		{
			/* 管理员更新页面 */
			adminsUpdate(request,response);
		}else if("adminsUpdateSubmit".equalsIgnoreCase(method))
		{
			/* 管理员更新提交操作 */
			adminsUpdateSubmit(request,response);
		}else
		{
			this.blank(request, response);
		}
	}
	/***
	 * 管理员更新提交页面
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException 
	 */
	private void adminsUpdateSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		System.out.println("==adminsUpdateSubmit==>管理员更新提交页面");
		/*根据id查询管理员*/
		String id = request.getParameter("id");
		Map<String,Object>condMap= new HashMap<String,Object>();
		condMap.put("id", id);
		condMap.put("extend", "true");
		/*准备对象*/
		AAdmins admins = this.usersDbService.findOneAdminsService(condMap);
		/* 我们要跳转页面,所以把admins信息放到request中;因为要在页面上显示 */
		request.setAttribute("one", admins);
		
		Map<String,Object> fileMap = new HashMap<String, Object>();
		boolean updateFlag = false ;
		/*接收参数，做分区*/
		String opertype = request.getParameter("operType");
		if("adminsUpdateInfo".equalsIgnoreCase(opertype))
		{
			/*修改个人信息*/
			/*接收参数*/
			String roleId = request.getParameter("roleId");
			String email = request.getParameter("email");
			/*修改个人信息，不可以修改密码*/
			String trueName = request.getParameter("trueName");
			String qq = request.getParameter("qq");
			String phone = request.getParameter("phone");
			String sex = request.getParameter("sex");
			String status = request.getParameter("status");
			/*处理参数*/
			int roleIdInt = Integer.parseInt(roleId);
			byte sexByte = Byte.parseByte(sex);
			byte statusByte = Byte.parseByte(status);
			 admins.setRoleId(roleIdInt);
			 admins.setEmail(email);
			 admins.setTrueName(trueName);
			 admins.setQq(qq);
			 admins.setPhone(phone);
			 admins.setSex(sexByte);
			 admins.setStatus(statusByte);
			 /*接收图片*/
			  Part part = request.getPart("file");
			 if(part !=null && part.getSubmittedFileName() !=null)
			 {
				  InputStream is= part.getInputStream();
				  fileMap.put("is", is);
				  fileMap.put("fileName",part.getSubmittedFileName() );
			 }
			 updateFlag = true ;
		}else if("adminsREsetPass".equalsIgnoreCase(opertype))
		{
			/*重置密码*/
			String password = request.getParameter("password");
			/*密码加密*/
			admins.setPassword(this.enuEncryptUtil.encodeStr(password));
			updateFlag = true ;
		}
		JSONObject resultJSON = new JSONObject();
		/* 更新数据库 */
		if(updateFlag)
		{
			/* 要更新数据库 */
			resultJSON = this.usersDbService.updateOneAdminsService(admins,fileMap);

		}else
		{
			/* 操作失败 */
			resultJSON.put(InfoEnum.VAR_CODE.getInfo(), InfoEnum.INFO_OPER_ERROR.getCode());
			resultJSON.put(InfoEnum.VAR_INFO.getInfo(), ConstatFinalUtil.INFO_JSON.getString(InfoEnum.INFO_OPER_ERROR.getCode() + ""));
		}
		
		this.printStr(request, response, resultJSON.toJSONString());
	}
	/***
	 * 打开更新页面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void adminsUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==adminsUpdate==>管理员更新页面");
		/*根据id查询管理员*/
		String id = request.getParameter("id");
		Map<String,Object>condMap= new HashMap<String,Object>();
		condMap.put("id",id);
		condMap.put("extend","true" );
		AAdmins admins = this.usersDbService.findOneAdminsService(condMap);
		/* 我们要跳转页面,所以把admins信息放到request中;因为要在页面上显示 */
		request.setAttribute("one", admins);
		/*路径*/
		String path = "" ;
		/*接收参数，做分区*/
		String operType = request.getParameter("operType");
		if("adminsInfo".equalsIgnoreCase(operType))
		{
			/*查看个人信息*/
			path = "/back/admins/adminsInfo" ;
		}else if("adminsUpdateInfo".equalsIgnoreCase(operType))
		{
			/*打开更新个人信息页面*/
			path = "/back/admins/adminsUpdateInfo" ;
			/* 查询所有状态为启用的角色(不能分页);前题我们得清楚记录不是很多
			 * 应该是角色的枚举(模仿着管理员的枚举写一个角色的枚举呢???)
			 *  */
			condMap.clear();
			condMap.put("status", "1");
			List<ARole> roleList = this.usersDbService.findCondListRoleService(null, condMap);
			request.setAttribute("roleList", roleList);
		}else if("adminsResetPass".equalsIgnoreCase(operType))
		{
			/*重置密码*/
			path = "/back/admins/adminsResetPass" ;
		}
		/*因为要把服务端跳转变成客户端跳转，心里得有数
		 * 修改Servlet,就要知道所有的request,setAttribute()已经不好用了，可以显示更换
		 * 
		 * */
		this.serverRedirect(request, response, path);
		
	}

	/***
	 * 管理员添加提交页面
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void adminsInsertSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		System.out.println("==adminsInsertSubmit==>打开管理员添加提交页面");
		/*接收参数*/
		String roleId = request.getParameter("roleId");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String trueName = request.getParameter("trueName");
		String qq = request.getParameter("qq");
		String phone = request.getParameter("phone");
		String sex = request.getParameter("sex");
		String status = request.getParameter("status");
		/*处理参数*/
		int roleIdInt = Integer.parseInt(roleId);
		 byte sexByte = Byte.parseByte(sex);
		 byte statusByte = Byte.parseByte(status);
		 /*new对象*/
		 AAdmins admins =  new AAdmins();
		 /*为参数赋值*/
		 admins.setRoleId(roleIdInt);
		 admins.setEmail(email);
		 admins.setPassword(password);
		 admins.setTrueName(trueName);
		 admins.setQq(qq);
		 admins.setPhone(phone);
		 admins.setSex(sexByte);
		 admins.setStatus(statusByte);
		 /*嗲用Service*/
		 JSONObject resultJSON = this.usersDbService.saveOneAdminsService(admins);
		 /*调用service方法执泥修改结果，目的是为了把结果通知给jsp*/
		 /*响应是json*/
		 this.printStr(request, response, resultJSON.toJSONString());
	}
	/***
	 * 打开管理员添加页面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void adminsInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==adminsInsert===");
		Map<String,Object> condMap = new HashMap<String, Object>();
		/* 查询所有状态为启用的角色(不能分页);前题我们得清楚记录不是很多
		 * 应该是角色的枚举(模仿着管理员的枚举写一个角色的枚举呢???)
		 *  */
		condMap.clear();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersDbService.findCondListRoleService(null, condMap);
		request.setAttribute("roleList", roleList);
		/* 直接跳转到管理员添加页面中 */
		this.serverRedirect(request, response, "/back/admins/adminsInsert");
		
	}
	/***
	 * 管理员列表
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void adminsList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("==AdminsBackServlet==adminsList");
		/* 分页工具类 */
		PageInfoUtil pageInfoUtil = proccedPageInfoUtil(request);
		/* 处理搜索条件 */
		Map<String, Object> condMap = proccedSearchCond(request);
			/*~~性别处理开始~~*/
			String sex = request.getParameter("sex");
			if(sex == null)
			{
				sex = "" ;
			}
			condMap.put("sex",sex);
			request.setAttribute("sex", sex);
			/*~~性别处理结束~~*/
			
			/*~roleId处理开始~*/
			String roleId = request.getParameter("roleId");
			if(roleId ==null)
			{
				roleId = "" ;
			}
			condMap.put("roleId", roleId);
			request.setAttribute("roleId", roleId);
			/*~roleId处理结束~*/
			condMap.put("extend","true");
		    List<AAdmins> adminsList= this.usersDbService.findCondListAdminsService(pageInfoUtil, condMap);
		    /*存储到四大作用域*/
		    request.setAttribute("list", adminsList);
		    request.setAttribute("pageInfoUtil", pageInfoUtil);
		    
		    /*查询到所有的状态为启用的角色（不能分页）；前提我们得清除记录不是很多
		     * 应该是角色的枚举(模仿管理员的枚举写一个角色的枚举)
		     * */
		    condMap.clear();
		    condMap.put("status", "1");
		    List<ARole>roleList = this.usersDbService.findCondListRoleService(null, condMap);
		    request.setAttribute("roleList", roleList);
		    
		    /*服务端跳转*/
		    this.serverRedirect(request, response,"/back/admins/adminsList");
		    
	}
	/***
	 * 退出
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		session.removeAttribute("lastLoginTime");
		session.removeAttribute("adminsSess");
		/*客户端跳转*/
		this.clientRedirect(request, response, "/NoLoginBackServlet?method=login");
		return ;
	}

	/**
	 * 欢迎页面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void welcome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.serverRedirect(request, response, "/back/admins/welcome");
	}
	/***
	 * 登录后首页
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void main(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/*服务器跳转*/
		this.serverRedirect(request, response, "/back/admins/main");
	}
}
